﻿/**
 * 2015-09-04
 * douzaixing
 * 完成前端分页控件和后端数据对象的对接 
 */
(function($) {
	var mergeParam = null;
	var defaultParam = {
		rows : 10,
		page : 1,
		grid : null,
		url : '',
		data : {},
		onSuccess : $.noop
	};

	function init(param) {
		mergeParam = $.extend(defaultParam, param);
		mergeParam.data.page = mergeParam.page;
		mergeParam.data.rows = mergeParam.rows;

		var pager = mergeParam.grid.datagrid('getPager');
		pager.pagination({
			onSelectPage : function(pageNumber, pageSize) {// 分页触发
				mergeParam.data.page = pageNumber;
				mergeParam.data.rows = pageSize;
				find();
			}
		});
		find();
	}

	function find(param) {
		mergeParam.grid.datagrid("getPager").pagination({
			pageSize : mergeParam.data.rows,
			pageNumber : mergeParam.data.page
		});// 重置
		mergeParam.grid.datagrid("loading"); // 加屏蔽
		var ajax = null;
		if(ajax) {
            ajax.abort();
        }
        ajax = $.ajax({
			type : "GET",
			dataType : "json",
			url : mergeParam.url,
			data : mergeParam.data,
			success : function(result) {
				if (result) {
					var obj = new Object();
					obj.total = result.totalCount;
					obj.rows = result.result;
					mergeParam.grid.datagrid('loadData', obj);// 这里的pageData是我自己创建的一个对象，用来封装获取的总条数，和数据，data.rows是我在控制器里面添加的一个map集合的键的名称
					mergeParam.grid.datagrid("loaded"); // 移除屏蔽
					mergeParam.onSuccess(obj);
				} else {
					mergeParam.grid.datagrid("loaded");
					$.messager.alert('错误', '网络异常，请稍后再试！', 'error');
				}
			},
			error : function(err) {
				$.messager.alert('操作提示', '获取信息失败，请联系管理员!', 'error');
				mergeParam.grid.datagrid("loaded"); // 移除屏蔽
			}
		});
	}

	$.extend({
		myPaginate : function(param) {
			init(param);
		},
	});
})(jQuery);

(function($) {
	var SplitPageDiv = function(ele, opt) {
		this.$element = ele,
	    this.defaults = {
			url : '',
			data : {},
			onLoadSuccess : $.noop,
			rows : 10,
			total : 0
	    },
	    this.options = $.extend({}, this.defaults, opt),
	    this.options.data.rows = this.options.rows,
	    this.options.current = this.options.current || 1,
	    this.options.data.page = this.options.current
	};
	
	SplitPageDiv.prototype = {
		initGrid : function() {
			var __this = this;
			var ajax = null;
			if(ajax) {
                ajax.abort();
          	}
            ajax = $.ajax({
				type : "GET",
				dataType : "JSON",
				url : this.options.url,
				data : this.options.data,
				success : function(result) {
					if (result) {
						if (result.done) {
							__this.options.total = result.data.context.total;
							__this.options.pageCount = __this.options.total % __this.options.data.rows == 0 
													? __this.Div(__this.options.total, __this.options.data.rows) 
													: __this.Div(__this.options.total, __this.options.data.rows) + 1;
							__this.options.onLoadSuccess(result.data, __this.options.current);
							__this.render(__this.$element, __this.options);
							__this.event(__this.$element, __this.options);
						} else {
							$.messager.alert('错误', result.msg, 'error');
						}
					} else {
						$.messager.alert('错误', '网络异常，请稍后再试！', 'error');
					}
				},
				error : function(err) {
					$.messager.alert('操作提示', '获取信息失败，请联系管理员!', 'error');
				}
			});
		},
		render : function(obj, args) {
			return (function(){
				obj.empty();
				if(args.current > 1){
					obj.append('<li class="prev"><a href="javascript:;">前一页</a></li>');
				}else{
					obj.append('<li class="prev disabled"><a href="javascript:;">前一页</a></li>');
				}
				if(args.current != 1 && args.current >= 4 && args.pageCount != 4){
					obj.append('<li><a href="javascript:;" class="tcdNumber">' + 1 + '</a></li>');
				}
				if(args.current-2 > 2 && args.current <= args.pageCount && args.pageCount > 5){
					obj.append('<li><a href="javascript:;">...</a></li>');
				}
				var start = args.current -2,end = args.current+2;
				if((start > 1 && args.current < 4)||args.current == 1){
					end++;
				}
				if(args.current > args.pageCount-4 && args.current >= args.pageCount){
					start--;
				}
				for (;start <= end; start++) {
					if(start <= args.pageCount && start >= 1){
						if(start != args.current){
							obj.append('<li><a href="javascript:;" class="tcdNumber">'+ start +'</a></li>');
						}else{
							obj.append('<li class="active"><a href="javascript:;" class="tcdNumber">'+ start +'</a></li>');
						}
					}
				}
				if(args.current + 2 < args.pageCount - 1 && args.current >= 1 && args.pageCount > 5){
					obj.append('<li><a href="javascript:;">...</a></li>');
				}
				if(args.current != args.pageCount && args.current < args.pageCount -2  && args.pageCount != 4){
					obj.append('<li><a href="javascript:;" class="tcdNumber">'+args.pageCount+'</a></li>');
				}
				
				if(args.current < args.pageCount){
					obj.append('<li class="next"><a href="javascript:;">后一页</a></li>');
				}else{
					obj.append('<li class="next disabled"><a href="javascript:;">后一页</a></li>');
				}
				
				obj.append('<li><span class="topages" style="font-size:14px;color:#2fa4e7;padding:0px;">&nbsp;&nbsp;到第\
						<input type="text" class="page_number" style="width: 50px;height:34px;color:#000;text-align:center;"\
						value="'+(args.current>args.pages?args.pages:args.current)+'" />页&nbsp;&nbsp;</span>\
						<button type="button" class="btn btn-default page_submit" style="height:35px;color:#2fa4e7;">确定</button></li>');
			})();
		},
		event : function(obj, args) {
			var __this = this;
			return (function(){
				obj.find("li>a.tcdNumber").unbind("click").click(function(){
					__this.options.current = parseInt($(this).text());
					__this.options.data.page = __this.options.current,
					__this.initGrid();
				});
				obj.find("li.prev").unbind("click").click(function(){
					__this.options.current = parseInt(args.current-1);
					__this.options.data.page = __this.options.current,
					__this.initGrid();
				});
				obj.find("li.next").unbind("click").click(function(){
					__this.options.current = parseInt(args.current+1);
					__this.options.data.page = __this.options.current,
					__this.initGrid();
				});
				obj.find("button.page_submit").unbind("click").click(function(){
					var value = $(__this.$element).find('input.page_number').val();
					var number = parseInt($.trim(value));
					var pages = __this.options.pageCount;
					if(isNaN(number)){
						$.messager.alert('错误', '请输入正确的数字！', 'error');
						return;
					} else if (number < 1) {
						number = 1;
					} else {
						number = number>pages?pages:number;
					}
					__this.options.data.page = number;
					__this.options.current = number;
					__this.initGrid();
				});
			})();
		},
		Div : function(exp1, exp2) {
			var n1 = Math.round(exp1);
			var n2 = Math.round(exp2);
			var rslt = n1 / n2;
			if (rslt >= 0) {
				rslt = Math.floor(rslt);
			} else {
				rslt = Math.ceil(rslt);
			}
			return rslt;
		}
	};
	
	$.fn.splitPage = function(options) {
		var splitPageDiv = new SplitPageDiv(this, options);
		return splitPageDiv.initGrid();
	};
})(jQuery);

(function($) {
	//控制台日志调试使用
	$.extend({
	    log: function(message) {
	        var now = new Date(),
	            y = now.getFullYear(),
	            m = now.getMonth() + 1,
	            d = now.getDate(),
	            h = now.getHours(),
	            min = now.getMinutes(),
	            s = now.getSeconds(),
	            time = y + '/' + m + '/' + d + ' ' + h + ':' + min + ':' + s;
	        console.log(time + ' My App: ' + message);
	    }
	});
	
	Date.prototype.Format = function (fmt) { //author: meizz 
	    var o = {
	        "M+": this.getMonth() + 1, //月份 
	        "d+": this.getDate(), //日 
	        "h+": this.getHours(), //小时 
	        "m+": this.getMinutes(), //分 
	        "s+": this.getSeconds(), //秒 
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
	        "S": this.getMilliseconds() //毫秒 
	    };
	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    return fmt;
	}
})(jQuery);